package com.vegetable.modules.service.finance.impl;

import com.vegetable.modules.mapper.finance.FinanceAgentDeliveryMapper;
import com.vegetable.modules.mapper.finance.FinancePurchaseDeliveryMapper;
import com.vegetable.modules.finance.service.ArrearsService;
import com.vegetable.modules.vo.finance.ArrearsStatisticsVO;
import com.vegetable.modules.vo.finance.ArrearsDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 欠款统计服务实现
 */
@Slf4j
@Service
public class ArrearsServiceImpl implements ArrearsService {
    
    @Autowired
    private FinanceAgentDeliveryMapper agentDeliveryMapper;
    
    @Autowired
    private FinancePurchaseDeliveryMapper purchaseDeliveryMapper;
    
    /**
     * 计算公司总欠款
     * @param agentId 代办人ID（可选）
     * @param customerId 客户ID（可选）
     * @param regionId 地域标志（可选）
     * @return 总欠款金额
     */
    @Override
    public BigDecimal calculateTotalArrears(Long agentId, Long customerId, Integer regionId) {
        BigDecimal agentArrears = calculateAgentArrears(agentId, regionId);
        BigDecimal purchaseArrears = calculatePurchaseArrears(customerId, regionId);
        return agentArrears.add(purchaseArrears);
    }
    
    /**
     * 计算代办欠款
     * @param agentId 代办人ID（可选）
     * @param regionId 地域标志（可选）
     * @return 代办欠款金额
     */
    @Override
    public BigDecimal calculateAgentArrears(Long agentId, Integer regionId) {
        return agentDeliveryMapper.calculateAgentArrears(agentId, regionId);
    }
    
    /**
     * 计算采购欠款
     * @param customerId 客户ID（可选）
     * @param regionId 地域标志（可选）
     * @return 采购欠款金额
     */
    @Override
    public BigDecimal calculatePurchaseArrears(Long customerId, Integer regionId) {
        return purchaseDeliveryMapper.calculatePurchaseArrears(customerId, regionId);
    }
    
    /**
     * 计算代办未对账金额
     * @param agentId 代办人ID（可选）
     * @param regionId 地域标志（可选）
     * @return 代办未对账金额
     */
    @Override
    public BigDecimal calculateAgentUnreconciled(Long agentId, Integer regionId) {
        return agentDeliveryMapper.calculateAgentUnreconciled(agentId, regionId);
    }
    
    /**
     * 计算代办已对账未付款金额
     * @param agentId 代办人ID（可选）
     * @param regionId 地域标志（可选）
     * @return 代办已对账未付款金额
     */
    @Override
    public BigDecimal calculateAgentUnpaid(Long agentId, Integer regionId) {
        return agentDeliveryMapper.calculateAgentUnpaid(agentId, regionId);
    }
    
    /**
     * 计算采购未对账金额
     * @param customerId 客户ID（可选）
     * @param regionId 地域标志（可选）
     * @return 采购未对账金额
     */
    @Override
    public BigDecimal calculatePurchaseUnreconciled(Long customerId, Integer regionId) {
        return purchaseDeliveryMapper.calculatePurchaseUnreconciled(customerId, regionId);
    }
    
    /**
     * 计算采购已对账未付款金额
     * @param customerId 客户ID（可选）
     * @param regionId 地域标志（可选）
     * @return 采购已对账未付款金额
     */
    @Override
    public BigDecimal calculatePurchaseUnpaid(Long customerId, Integer regionId) {
        return purchaseDeliveryMapper.calculatePurchaseUnpaid(customerId, regionId);
    }
    
    /**
     * 获取欠款统计详情
     * @param agentId 代办人ID（可选）
     * @param customerId 客户ID（可选）
     * @param regionId 地域标志（可选）
     * @return 欠款统计详情
     */
    @Override
    public ArrearsStatisticsVO getArrearsStatistics(Long agentId, Long customerId, Integer regionId) {
        ArrearsStatisticsVO vo = new ArrearsStatisticsVO();
        vo.setAgentId(agentId);
        vo.setCustomerId(customerId);
        vo.setRegionId(regionId);
        
        // 计算代办相关金额
        BigDecimal agentUnreconciled = calculateAgentUnreconciled(agentId, regionId);
        BigDecimal agentUnpaid = calculateAgentUnpaid(agentId, regionId);
        BigDecimal agentArrears = calculateAgentArrears(agentId, regionId);
        
        // 计算采购相关金额
        BigDecimal purchaseUnreconciled = calculatePurchaseUnreconciled(customerId, regionId);
        BigDecimal purchaseUnpaid = calculatePurchaseUnpaid(customerId, regionId);
        BigDecimal purchaseArrears = calculatePurchaseArrears(customerId, regionId);
        
        // 计算总金额
        BigDecimal totalUnreconciled = agentUnreconciled.add(purchaseUnreconciled);
        BigDecimal totalUnpaid = agentUnpaid.add(purchaseUnpaid);
        BigDecimal totalArrears = agentArrears.add(purchaseArrears);
        
        // 设置VO属性
        vo.setAgentUnreconciled(agentUnreconciled);
        vo.setAgentUnpaid(agentUnpaid);
        vo.setAgentArrears(agentArrears);
        
        vo.setPurchaseUnreconciled(purchaseUnreconciled);
        vo.setPurchaseUnpaid(purchaseUnpaid);
        vo.setPurchaseArrears(purchaseArrears);
        
        vo.setTotalUnreconciled(totalUnreconciled);
        vo.setTotalUnpaid(totalUnpaid);
        vo.setTotalArrears(totalArrears);
        
        return vo;
    }
    
    /**
     * 批量获取多个代办人的欠款统计
     * @param agentIds 代办人ID列表
     * @param regionId 地域标志（可选）
     * @return 欠款统计列表
     */
    @Override
    public List<ArrearsStatisticsVO> getAgentArrearsList(List<Long> agentIds, Integer regionId) {
        List<ArrearsStatisticsVO> result = new ArrayList<>();
        if (agentIds != null && !agentIds.isEmpty()) {
            for (Long agentId : agentIds) {
                ArrearsStatisticsVO vo = new ArrearsStatisticsVO();
                vo.setAgentId(agentId);
                vo.setRegionId(regionId);
                
                // 计算代办相关金额
                BigDecimal agentUnreconciled = calculateAgentUnreconciled(agentId, regionId);
                BigDecimal agentUnpaid = calculateAgentUnpaid(agentId, regionId);
                BigDecimal agentArrears = calculateAgentArrears(agentId, regionId);
                
                // 设置VO属性
                vo.setAgentUnreconciled(agentUnreconciled);
                vo.setAgentUnpaid(agentUnpaid);
                vo.setAgentArrears(agentArrears);
                
                // 采购相关金额为0，因为只查询代办人
                vo.setPurchaseUnreconciled(BigDecimal.ZERO);
                vo.setPurchaseUnpaid(BigDecimal.ZERO);
                vo.setPurchaseArrears(BigDecimal.ZERO);
                
                // 设置总金额
                vo.setTotalUnreconciled(agentUnreconciled);
                vo.setTotalUnpaid(agentUnpaid);
                vo.setTotalArrears(agentArrears);
                
                result.add(vo);
            }
        }
        return result;
    }
    
    /**
     * 批量获取多个客户的欠款统计
     * @param customerIds 客户ID列表
     * @param regionId 地域标志（可选）
     * @return 欠款统计列表
     */
    @Override
    public List<ArrearsStatisticsVO> getCustomerArrearsList(List<Long> customerIds, Integer regionId) {
        List<ArrearsStatisticsVO> result = new ArrayList<>();
        if (customerIds != null && !customerIds.isEmpty()) {
            for (Long customerId : customerIds) {
                ArrearsStatisticsVO vo = new ArrearsStatisticsVO();
                vo.setCustomerId(customerId);
                vo.setRegionId(regionId);
                
                // 计算采购相关金额
                BigDecimal purchaseUnreconciled = calculatePurchaseUnreconciled(customerId, regionId);
                BigDecimal purchaseUnpaid = calculatePurchaseUnpaid(customerId, regionId);
                BigDecimal purchaseArrears = calculatePurchaseArrears(customerId, regionId);
                
                // 设置VO属性
                vo.setPurchaseUnreconciled(purchaseUnreconciled);
                vo.setPurchaseUnpaid(purchaseUnpaid);
                vo.setPurchaseArrears(purchaseArrears);
                
                // 代办相关金额为0，因为只查询客户
                vo.setAgentUnreconciled(BigDecimal.ZERO);
                vo.setAgentUnpaid(BigDecimal.ZERO);
                vo.setAgentArrears(BigDecimal.ZERO);
                
                // 设置总金额
                vo.setTotalUnreconciled(purchaseUnreconciled);
                vo.setTotalUnpaid(purchaseUnpaid);
                vo.setTotalArrears(purchaseArrears);
                
                result.add(vo);
            }
        }
        return result;
    }
    
    /**
     * 获取欠款明细列表
     * @param regionId 地域标志（可选）
     * @return 欠款明细列表
     */
    @Override
    public List<ArrearsDetailVO> getArrearsDetailList(Integer regionId) {
        List<ArrearsDetailVO> result = new ArrayList<>();
        
        // 获取代办未打款明细列表
        List<ArrearsDetailVO> agentArrearsDetailList = agentDeliveryMapper.getAgentArrearsDetailList(regionId);
        result.addAll(agentArrearsDetailList);
        
        // 获取采购未打款明细列表
        List<ArrearsDetailVO> purchaseArrearsDetailList = purchaseDeliveryMapper.getPurchaseArrearsDetailList(regionId);
        result.addAll(purchaseArrearsDetailList);
        result.sort(Comparator
                .comparing(ArrearsDetailVO::getArrearsAmount,
                        Comparator.nullsLast(Comparator.naturalOrder())) // 处理 null 并自然排序
                .reversed()); // 反转实现倒序
        return result;
    }
}